//
//  UPContactManager.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/27.
//

#import "UPContactManager.h"

@implementation UPContactManager

+ (instancetype)shared {
    static UPContactManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _store = [[CNContactStore alloc] init];
    }
    return self;
}

- (void)requestAccessWithCompletion:(void (^)(BOOL))completion {
    [self.store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
            completion(status == CNAuthorizationStatusAuthorized);
        });
    }];
}

- (void)fetchAllContactsWithCompletion:(void (^)(NSArray<CNContact *> * _Nullable, NSError * _Nullable))completion {
    NSArray<id<CNKeyDescriptor>> *keys = @[
        CNContactIdentifierKey,
        CNContactGivenNameKey,
        CNContactFamilyNameKey,
        CNContactPhoneNumbersKey,
        CNContactEmailAddressesKey
    ];
    
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        @try {
            CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
            NSMutableArray<CNContact *> *contacts = [NSMutableArray array];
            
            NSError *fetchError;
            [self.store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
                [contacts addObject:contact];
            }];
            
            if (fetchError) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completion(nil, fetchError);
                });
                return;
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                completion([contacts copy], nil);
            });
        } @catch (NSException *exception) {
            NSError *error = [NSError errorWithDomain:@"UPContactManager"
                                                 code:-1
                                             userInfo:@{NSLocalizedDescriptionKey: exception.reason ?: @"Unknown error"}];
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(nil, error);
            });
        }
    });
}

- (NSDictionary<NSString *, id> *)formattedContactInfo:(CNContact *)contact {
    NSMutableString *phoneNumbersString = [NSMutableString string];
    for (CNLabeledValue<CNPhoneNumber *> *phoneNumber in contact.phoneNumbers) {
        if (phoneNumbersString.length > 0) {
            [phoneNumbersString appendString:@","];
        }
        [phoneNumbersString appendString:phoneNumber.value.stringValue];
    }
    
    return @{
        @"quindecimlocalety": [NSString stringWithFormat:@"%@%@", contact.familyName, contact.givenName],
        @"third": [phoneNumbersString copy]
    };
}

@end
